namespace RBAC.Write.Api.Application.Handler.QualityHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.QualityManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.QualityCommand;

    /// <summary>
    /// 新增质量工单 处理器。
    /// </summary>
    /// <remarks>
    /// 主要逻辑：
    /// 1. 参数校验：<c>Title</c> 必填，<c>ProductId</c> > 0。
    /// 2. 生成工单号：格式 <c>QOyyMMddHHmmss</c>，并做唯一性校验。
    /// 3. 写入 <see cref="QualityOrder"/> 主表；返回新建记录 Id。
    /// 4. 统一异常处理与日志记录。
    /// </remarks>
    /// </summary>
    public class QualityOrderAddHandler : IRequestHandler<QualityOrderAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<QualityOrder> _orderRepo;
        private readonly ILogger<QualityOrderAddHandler> _logger;

        public QualityOrderAddHandler(IBaseRepository<QualityOrder> orderRepo, ILogger<QualityOrderAddHandler> logger)
        {
            _orderRepo = orderRepo;
            _logger = logger;
        }

        /// <summary>
        /// 处理“新增质量工单”请求。
        /// </summary>
        /// <param name="request">新增命令实体。</param>
        /// <param name="cancellationToken">取消令牌。</param>
        /// <returns>返回包含新建记录 Id 的 <see cref="APIResult{T}"/>。</returns>
        public Task<APIResult<int>> Handle(QualityOrderAddCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                // 检查是否被取消
                cancellationToken.ThrowIfCancellationRequested();

                // 参数校验：标题必填
                if (string.IsNullOrWhiteSpace(request.Title))
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "工单标题不能为空", Data = 0 });
                // 参数校验：产品Id > 0
                if (request.ProductId is null or <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "产品Id无效", Data = 0 });

                // 生成工单号：QO + yyMMddHHmmss（秒级，若并发较高可改为自增/雪花）
                var code = "QO" + DateTime.Now.ToString("yyMMddHHmmss");
                // 唯一性校验
                var exist = _orderRepo.GetFirstOrDefault("OrderNo = @OrderNo AND IsDeleted = 0", new { OrderNo = code });
                if (exist != null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "工单号已存在，请重试", Data = 0 });

                // 组装实体对象
                var entity = new QualityOrder
                {
                    OrderNo = code,
                    Title = request.Title!.Trim(),
                    SourceWorkOrderNo = request.SourceWorkOrderNo,
                    ProductId = request.ProductId,
                    ProductName = request.ProductName,
                    OwnerUserId = request.OwnerUserId,
                    OwnerUserName = request.OwnerUserName,
                    Status = 0,
                    Remark = request.Remark
                };
                if (!string.IsNullOrWhiteSpace(request.CreateUser))
                    entity.CreateUser = request.CreateUser!;

                // 仓储：插入并返回新Id
                var newId = _orderRepo.Create(entity);
                // 返回语义：newId > 0 视为成功
                result.Code = newId > 0 ? APIEnums.Success : APIEnums.Fail;
                result.Msg = newId > 0 ? "新增质量工单成功" : "新增质量工单失败";
                result.Data = newId;
            }
            catch (OperationCanceledException)
            {
                // 捕获取消异常
                _logger?.LogWarning("新增质量工单被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                // 统一异常处理与日志
                _logger?.LogError(ex, "新增质量工单异常: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "新增质量工单异常: " + ex.Message;
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
